package io.renren.modules.lucky.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.DateUtils;
import io.renren.modules.lucky.dto.background.LuckyCallBackReq;
import io.renren.modules.lucky.entity.*;
import io.renren.modules.lucky.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
public class LuckyReportTask {
    private static final Logger logger = LoggerFactory.getLogger(LuckyReportTask.class);
    private static final String LUCKY_REPORT_REDIS_KEY = "lucky:report:";

    private static final String LUCKY_SESSION_ID_PLAT_CODE = "lucky:report:sessionId:";


    @Autowired
    private LuckyRecordService luckyRecordService;

    @Autowired
    private LuckyUserConfigService luckyUserConfigService;

    @Autowired
    private PhoneLocationService phoneLocationService;

    @Autowired
    private LuckyOrderService luckyOrderService;

    @Autowired
    private RedisUtils redisUtil;

    // 每日凌晨一点执行
    @Scheduled(cron = "0 0 1 * * ?")
    public void saveReport() {

        try {
            //读取配置表，获取所有的平台商户
            List<LuckyUserConfigEntity> configList = luckyUserConfigService.getAll();

            for (LuckyUserConfigEntity config : configList) {
                logger.error("开始处理商户code为{}的数据", config.getPlatCode());
                //读取缓存 保存数据
                String lastDayStr = DateUtils.getYesterday(DateUtils.DATE_PATTERN);
                //String redisKey = LUCKY_REPORT_REDIS_KEY + lastDayStr + ":" + config.getPlatCode();
                String redisKey = "lucky:report:2025-01-16:9999";
                Map<String, Object> redisData = redisUtil.hGetAll(redisKey);
                if (MapUtil.isNotEmpty(redisData)) {
                    // 保存入库
                    LuckyRecordEntity recordEntity = new LuckyRecordEntity();
                    recordEntity.setPlatCode(config.getPlatCode());

                    // 批量更新
                    int batchSize = 1000;
                    List<LuckyRecordEntity> recordList = new ArrayList<>();
                    List<LuckyOrderEntity> orderList = new ArrayList<>();
                    for (Map.Entry<String, Object> entry : redisData.entrySet()) {
                        Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();

                        // 添加到批量列表
                        LuckyRecordEntity entity = new LuckyRecordEntity();
                        //因为是隔日 所以日期写昨日
                        entity.setCreateTime((Date) valueMap.get("createTime"));
                        entity.setUv(1);

                        String phone = null;
                        String province = null;
                        String city = null;
                        String isp = null;
                        String district = null;

                        if (valueMap.get("phone") != null) {
                            phone = (String) valueMap.get("phone");
                            entity.setPhone(phone);
                        }

                        if (valueMap.get("province") != null) {
                            province = (String) valueMap.get("province");
                            city = (String) valueMap.get("city");
                            isp = (String) valueMap.get("isp");
                            district = (String) valueMap.get("district");

                            entity.setProvince(province);
                            entity.setCity(city);
                            entity.setIsp(isp);
                            entity.setDistrict(district);
                        } else {
                            PhoneLocationEntity locationEntity = phoneLocationService.getLocation(phone);
                            if (ObjectUtil.isNotEmpty(locationEntity)) {
                                province = locationEntity.getProvince();
                                city = locationEntity.getCity();
                                isp = locationEntity.getIsp();

                                entity.setProvince(province);
                                entity.setCity(city);
                                entity.setIsp(isp);
                            }
                        }


                        entity.setPlatCode(config.getPlatCode());

                        entity.setIp((String) valueMap.get("ip"));
                        entity.setSessionId((String) valueMap.get("sessionId"));


                        if (valueMap.get("pointNum") != null) {
                            entity.setPointNum((Integer) valueMap.get("pointNum"));
                        }
                        if (valueMap.get("isClick") != null) {
                            entity.setClicks((Integer) valueMap.get("isClick"));
                        }
                        entity.setForecastRevenue(new BigDecimal(config.getForecastRevenueRatio()));
                        if (valueMap.get("mediaId") != null) {
                            entity.setMediaId((String) valueMap.get("mediaId"));
                        }
                        if (valueMap.get("errCode") != null) {
                            entity.setErrCode((String) valueMap.get("errCode"));
                        }
                        if (valueMap.get("errMsg") != null) {
                            entity.setErrMsg((String) valueMap.get("errMsg"));
                        }
                        if (valueMap.get("curUrl") != null) {
                            entity.setCurrentUrl((String) valueMap.get("curUrl"));
                        }
                        if (valueMap.get("preUrl") != null) {
                            entity.setReferrerUrl((String) valueMap.get("preUrl"));
                        }

                        recordList.add(entity);


                        //订单
                        // 处理 businessId
                        Set<String> businessIdList = (Set<String>) valueMap.get("businessIdList");
                        if (CollectionUtil.isNotEmpty(businessIdList)) {
                            logger.info("处理订单数据Start");
                            for (String businessId : businessIdList) {
                                String jsonStr = valueMap.get(businessId).toString();
                                List<LuckyCallBackReq> businessList = JSON.parseArray(jsonStr, LuckyCallBackReq.class);
                                for (LuckyCallBackReq dto : businessList) {
                                    LuckyOrderEntity orderEntity = new LuckyOrderEntity();
                                    //订单
                                    orderEntity.setCity(city);
                                    orderEntity.setIsp(isp);
                                    orderEntity.setProvince(province);

                                    orderEntity.setSessionId(dto.getSessionId());
                                    orderEntity.setPlatCode(config.getPlatCode());
                                    orderEntity.setPhone(phone);
                                    orderEntity.setIp((String) valueMap.get("ip"));

                                    orderEntity.setBusinessId(businessId);
                                    orderEntity.setBusinessName(dto.getBusinessName());
                                    orderEntity.setBusinessAmount(new BigDecimal(dto.getBusinessAmount()));

                                    String formattedDate = DateUtils.coverISODate(dto.getOrderTime(), DateUtils.DATE_TIME_PATTERN);
                                    orderEntity.setOrderTime(formattedDate);
                                    if (valueMap.get("mediaId") != null) {
                                        entity.setMediaId((String) valueMap.get("mediaId"));
                                    }
                                    orderList.add(orderEntity);
                                }
                            }
                        }
                        if (orderList.size() >= batchSize) {
                            boolean orderFlag = luckyOrderService.insertBatch(orderList);
                            logger.info("订单数据处理结果：{}", orderFlag);
                            orderList.clear();
                        }

                        // 批量保存
                        if (recordList.size() >= batchSize) {
                            boolean recordFlag = luckyRecordService.insertBatch(recordList);
                            logger.info("埋点数据处理结果：{}", recordFlag);
                            recordList.clear();
                        }
                    }

                    // 保存剩余的记录
                    if (!recordList.isEmpty()) {
                        luckyRecordService.insertBatch(recordList);
                    }
                    if (!orderList.isEmpty()) {
                        luckyOrderService.insertBatch(orderList);
                    }
                }
                //删除redis记录
                //redisUtil.delete(redisKey);
                logger.info("商户code为{}的数据处理完成", config.getPlatCode());
            }
        } catch (Exception e) {
            logger.error("定时任务：处理埋点数据异常", e);
        }
    }
}
